package com.api.gbhg.liuwenbo.version3.api;

import com.alibaba.fastjson.JSONObject;
import com.api.gbhg.liuwenbo.commons.entitis.CommonResult;
import com.api.gbhg.liuwenbo.commons.entitis.StatusMsg;
import com.api.gbhg.liuwenbo.commons.utils.CheckUtil;
import com.api.gbhg.liuwenbo.commons.utils.Util;
import com.api.gbhg.liuwenbo.version3.pojo.RtExpensesPay;
import com.customization.commons.LogTool;
import com.google.common.base.Joiner;
import weaver.conn.RecordSet;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.*;

/**
 * @Description 报销细项支出-经费科报表
 * @Version 1.0
 * @Author  lwb
 * @Date 2023.4.14
 */
@Path("v3/RtExpensesPay")
public class RtExpensesPayApi {

    protected static ArrayList<Object> checkKey = new ArrayList<>();
    private RecordSet rst = new RecordSet();

    private static LogTool logTool = new LogTool("/log/gbhg/report/RtExpensesPayApi",false);
    static {
        checkKey.add("bmysjjfl");//部门经济分类
        checkKey.add("dfczbkxm");//dt表里的dfczbkxm字段
        checkKey.add("fzysrfl");//非中央收入分类
        checkKey.add("pageNumber");
        checkKey.add("zfysjjfl");//dt表里的zfysjjfl
        checkKey.add("dygnkmbid");//27_11"(或者28_xx 财政拨款时才有)
        checkKey.add("pageSize");
        checkKey.add("srlx");//:0-财政拨款 1-非财政
        checkKey.add("ysly");//上年/当年/全部
        checkKey.add("jbbm");//经办部门的id
        checkKey.add("year");//经办部门的id
    }

    @POST
    @Path("/getREPList")
    @Produces(MediaType.APPLICATION_JSON)
    public String getREPList(Map param){
        logTool.writeLog("接收参数："+param);
        if (!CheckUtil.isParamEmpty(param,checkKey))
            return new CommonResult(StatusMsg.CODE_400).toJSONString();

        List<RtExpensesPay> resultData = new LinkedList<>();
        try {
            if (param.get("srlx").toString().equals("0")){
                //财政拨款
                resultData.addAll(getZykmData(param));
            }else if(param.get("srlx").toString().equals("1")){
                //非财政拨款
                resultData.addAll(getFzyData(param));
            }else{
                //全部
                resultData.addAll(getZykmData(param));
                List<RtExpensesPay> fzyData = getFzyData(param);
                resultData.addAll(getFzyData(param));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult<>(500,e.toString()).toJSONString();
        }

        return new CommonResult<>(StatusMsg.CODE_200, resultData).toJSONString();
    }

    public List<RtExpensesPay> getFzyData(Map param) throws Exception{
        String yslyName = "";
        String ysly = param.get("ysly").toString();
        if (!ysly.isEmpty())
            yslyName = ysly.equals("0")?"当年预算":"上年结转";

        RecordSet rs = new RecordSet();
        String sql = "select ff.id,ff.szfl,fs.mc from uf_fzysr ff left join uf_srysfl fs on ff.szfl = fs.id where dw = 1 and nf="+param.get("year").toString();
        if (!param.get("fzysrfl").toString().isEmpty())
            sql+=" and ff.szfl = "+param.get("fzysrfl")+" ";
        rs.executeQuery(sql);
        List<RtExpensesPay> list = new LinkedList<>();
        while (rs.next()){
            RtExpensesPay bean = new RtExpensesPay();
            bean.setName(rs.getString("mc")+yslyName);

            if (ysly.equals("")) {
                //全部
                bean.setName(rs.getString("mc")+"上年预算");
                List<RtExpensesPay> snys = getZydt1Data(rs.getString("szfl"), "0", param, false);
                if (snys.size()>0){
                    bean.setXj(getZydt1Data(rs.getString("szfl"),"0",param,false));
                    list.add(bean);
                }

                RtExpensesPay bean1 = new RtExpensesPay();
                bean1.setName(rs.getString("mc")+"当年预算");
                List<RtExpensesPay> dnys = getZydt1Data(rs.getString("szfl"), "1", param, false);
                if (dnys.size()>0){
                    bean1.setXj(getZydt1Data(rs.getString("szfl"),"1",param,false));
                    list.add(bean1);
                }
            }else if(ysly.equals("0")){
                //上年
                List<RtExpensesPay> snys = getZydt1Data(rs.getString("szfl"), "0", param, false);
                if (snys.size()>0){
                    bean.setXj(getZydt1Data(rs.getString("szfl"),"0",param,false));
                    list.add(bean);
                }
            }else if(ysly.equals("1")){
                //当年
                List<RtExpensesPay> dnys = getZydt1Data(rs.getString("szfl"), "1", param, false);
                if (dnys.size()>0){
                    bean.setXj(getZydt1Data(rs.getString("szfl"),"1",param,false));
                    list.add(bean);
                }

            }
        }
        return list;
    }

    public void getFzyXmData(String fzyid,String flmc,String flid,Map param){
        RecordSet rs = new RecordSet();
        String sql = "";
    }

    /**
     * 获取中央科目级数据
     * @param param
     *          参数
     * @return
     * @throws Exception
     */
    public List<RtExpensesPay> getZykmData(Map param)throws Exception{
        RecordSet rs = new RecordSet();
        String sql = "select * from uf_zyczbksr_km where dw = 1 and srnf="+param.get("year");
        String[] dygnkmbid = param.get("dygnkmbid").toString().split("_");
        String xjid = "";
        //判断dygnkmbid参数
        if (!param.get("dygnkmbid").toString().isEmpty()){
            if (dygnkmbid[0].equals("27") || dygnkmbid[0].equals("90")){
                sql+=" and id = "+dygnkmbid[1]+" ";
            }else if(dygnkmbid[0].equals("28") || dygnkmbid[0].equals("91")){
                sql+=" and id = (select szgnkm from uf_zyczbksr_xj where id = "+dygnkmbid[1]+") ";
                xjid = dygnkmbid[1];
            }
        }
        rs.executeQuery(sql);
        List<RtExpensesPay> list = new LinkedList<>();
        while (rs.next()){

            String ysly = param.get("ysly").toString();
            if (ysly.equals("")){
                //全部
                list.addAll(getZyxjDataName(rs.getString("kmdm"),"0",rs.getString("id"),xjid,param));
                list.addAll(getZyxjDataName(rs.getString("kmdm"),"1",rs.getString("id"),xjid,param));
            }else if(ysly.equals("0")){
                //上年
                list.addAll(getZyxjDataName(rs.getString("kmdm"),"0",rs.getString("id"),xjid,param));
            }else if(ysly.equals("1")){
                //当年
                list.addAll(getZyxjDataName(rs.getString("kmdm"),"1",rs.getString("id"),xjid,param));
            }
        }
        return list;
    }

    public List<RtExpensesPay> getZyxjDataName(String kmdm,String ysly,String kmid,String xjId,Map param)throws Exception{
        String yslyName = ysly.equals("0")?"当年预算":"上年预算";

        RecordSet rs = new RecordSet();
        String sql = "select * from uf_zyczbksr_xj where ";
        if (!xjId.isEmpty()){
            //指定id
            sql+= " id = "+xjId+" ";
        }else{
            sql+=" szgnkm = "+kmid+" and sjzxsr is null  ";
        }
        rs.executeQuery(sql);
        List<RtExpensesPay> list = new LinkedList<>();
        while (rs.next()){
            RtExpensesPay bean = new RtExpensesPay();
            bean.setName(kmdm+"-"+rs.getString("srzx")+yslyName);
            String zxsrId = getZxsrId(rs.getString("id"));
            List<RtExpensesPay> dt1Data = getZydt1Data(zxsrId, ysly,param,true);
            if (dt1Data.size()==0)
                continue;
            bean.setXj(dt1Data);
            list.add(bean);
        }
        return list;
    }

    public String getZxsrId(String zxsrId){
        String sql = " select id from uf_zyczbksr_xj where sjzxsr in("+zxsrId+") ";
        rst.executeQuery(sql);

        if (rst.getCounts()>0){
            List<String> ids = new LinkedList<>();
            while (rst.next()){
                ids.add(rst.getString("id"));
            }
            return Joiner.on(",").join(ids.toArray());
        }else{
            return zxsrId;
        }
    }

    /**
     * 获取明细数据
     * @param id
     * @param ysly
     * @param param
     * @param iszy
     * @return
     * @throws Exception
     */
    public List<RtExpensesPay> getZydt1Data(String id,String ysly,Map param,boolean iszy) throws Exception{

        String sql = "select  sum(dt1.sqbxje) as sqbxje,kj.jbbm,kj.shrq,dt1.bmjjzcfl,dt1.zfjjzcfl,dt1.ysly,dt1.zcqd,kj.requestid,dt1.lcid from uf_bxjl_kj_dt1 dt1 left join uf_bxjl_kj kj on dt1.lcid = kj.lcid \n" +
                "where dt1.ysxm in (select lcjlsqjlid from uf_jingfei_version where dlhsdw=1) and dt1.ysly="+ysly+" \n";
        if (iszy) {
            //中央
            sql += " and dt1.dygnkmbid in (" + id + ")  and dt1.kmjxj=1 \n";
        }else{
            //非中央
            sql += " and dt1.fzysrfl = "+id+" \n";
            if (!param.get("dfczbkxm").toString().isEmpty())
                sql += " and dt1.czdfczbkxm = "+param.get("dfczbkxm")+" \n";
        }
        //处理条件
        if (!param.get("bmysjjfl").toString().isEmpty())
            sql+=" and dt1.bmjjzcfl = "+param.get("bmysjjfl")+" \n";
        if (!param.get("zfysjjfl").toString().isEmpty())
            sql+=" and dt1.zfjjzcfl = "+param.get("zfysjjfl")+" \n";
        if (!param.get("jbbm").toString().isEmpty())
            sql+=" and kj.jbbm = "+param.get("jbbm")+" \n";
        sql+=" and year(kj.shrq) = "+param.get("year")+" \n";
        sql+="group by kj.jbbm,kj.shrq,dt1.bmjjzcfl,dt1.zfjjzcfl,dt1.ysly,dt1.zcqd,kj.requestid,dt1.lcid ";
        rst.executeQuery(sql);
        List<RtExpensesPay> list = new LinkedList<>();

        //记录经办部门坐标
        Map<String,Integer> checkMap = new HashMap<>();
        int listIx = 0;
        while (rst.next()){
            RtExpensesPay bean = new RtExpensesPay();

            RtExpensesPay DataBean = new RtExpensesPay();
            DataBean.setRequestid(rst.getString("lcid"));
            DataBean.setLcmc(Util.getRequestInfo(rst.getString("lcid"),"requestmark")+"(审核:"+rst.getString("shrq")+")");
            DataBean.setBxje(rst.getString("sqbxje"));
            DataBean.setBmjjfl(rst.getString("bmjjzcfl"));
            DataBean.setZfjjfl(rst.getString("zfjjzcfl"));
            DataBean.setShrq(rst.getString("shrq"));

            if (list.size()==0 || !checkMap.containsKey(rst.getString("jbbm"))){
                bean.setDwmc(Util.getCompanyName(rst.getString("jbbm")));
                List<RtExpensesPay> tempList = new LinkedList<>();
                tempList.add(DataBean);
                bean.setXj(tempList);
                list.add(bean);
                checkMap.put(rst.getString("jbbm"),listIx);
                listIx++;
            }else{
                List<RtExpensesPay> jbbm = list.get(checkMap.get(rst.getString("jbbm"))).getXj();
                jbbm.add(DataBean);
            }
        }
        return list;
    }
}
